#include <iostream>
#include "AbstractDatabase.h"
#include "WKTFileFormat.h"

/**
 *
 **/
WKTFileFormat::WKTFileFormat(PFSInfo info) : AbstractFileFormat(info)
{
    this->wkt = "";
    this->sizeParam = WKT_FILESIZE_PARAM;
}

/**
 *
 **/
int WKTFileFormat::close(PFSInfo info)
{
    return 0;
}


/**
 *
 **/
WKTFileFormat::~WKTFileFormat() {
    //delete this->wkt;
}

/**
 *
 **/
int WKTFileFormat::read(PFSInfo info){
    if(!this->created){
        this->result = info->filesystem->getDBConnection()->select(&info->database, &info->schema, &info->table, OPTION_ONLY_GEOM);
        while( this->result->hasMore() && info->offset + info->size > wkt.size()) {
            this->row = this->result->fetch();
            this->wkt.append(this->row->getFieldValue(0));
            this->wkt.append(ENDL);
        }
        this->created = true;
        delete this->result;
    }

    if (info->offset < wkt.size()) {
        if (info->offset + info->size > wkt.size())
        {
            info->size = wkt.size() - info->offset;
        }
        memcpy(info->readBuffer, wkt.c_str() + info->offset, info->size);
    }
    else{
        info->size = 0;
    }
    return  info->size;
}

/**
 *
 **/
int WKTFileFormat::write(PFSInfo info)
{
    return -ENOPROTOOPT; //write mode not supported
}
